package com.chuanke.ckfamily.service.common.impl;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.chuanke.ckfamily.dao.user.model.UserRelation;
import com.chuanke.ckfamily.service.constant.MsgEunm;
import com.chuanke.ckfamily.service.constant.SpecialRelationConstant;
import com.chuanke.ckfamily.service.constant.UserRelationType;
import com.chuanke.ckfamily.service.social.SpecialRelationService;
import com.chuanke.ckfamily.service.user.UserRelationService;
import com.chuanke.ckfamily.service.user.UserService;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chuanke.ckfamily.dao.social.model.Family;
import com.chuanke.ckfamily.dao.social.model.FamilyMember;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.base.FailCode;
import com.chuanke.ckfamily.service.common.TeamCreateLogService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.exception.WyException;
import com.weijie.core.wy.WyDefaultResponse;
import com.weijie.core.wy.WyHelper;
import com.weijie.core.wy.WyRequest;
import com.weijie.core.wy.WyResponse;
import com.weijie.core.wy.model.TeamJoinTeams;
import com.weijie.core.wy.model.TeamListTeamMute;
import com.weijie.core.wy.response.WyTeamCreateResponse;
import com.weijie.core.wy.response.WyTeamJoinTeamsResponse;
import com.weijie.core.wy.response.WyTeamListTeamMuteResponse;
import com.weijie.core.wy.response.WyUserCreateResponse;
import com.weijie.core.wy.response.WyUserRefreshTokenResponse;
import com.weijie.corel.wy.request.WyFriendAddRequest;
import com.weijie.corel.wy.request.WyFriendDeleteRequest;
import com.weijie.corel.wy.request.WyFriendUpdateRequest;
import com.weijie.corel.wy.request.WyMsgSendAttachMsgRequest;
import com.weijie.corel.wy.request.WyMsgSendMsgRequest;
import com.weijie.corel.wy.request.WyTeamAddRequest;
import com.weijie.corel.wy.request.WyTeamChangeOwnerRequest;
import com.weijie.corel.wy.request.WyTeamCreateRequest;
import com.weijie.corel.wy.request.WyTeamJoinTeamsRequest;
import com.weijie.corel.wy.request.WyTeamKickRequest;
import com.weijie.corel.wy.request.WyTeamLeaveRequest;
import com.weijie.corel.wy.request.WyTeamListTeamMuteRequest;
import com.weijie.corel.wy.request.WyTeamMuteTeamRequest;
import com.weijie.corel.wy.request.WyTeamMuteTlistRequest;
import com.weijie.corel.wy.request.WyTeamRemoveRequest;
import com.weijie.corel.wy.request.WyTeamUpdateRequest;
import com.weijie.corel.wy.request.WyUserCreateRequest;
import com.weijie.corel.wy.request.WyUserRefreshTokenRequest;
import com.weijie.corel.wy.request.WyUserSetSpecialRelationRequest;
import com.weijie.corel.wy.request.WyUserUpdateUinfoRequest;

@Service
public class WyServiceImpl implements WyService {
	
	//系统推送使用accid
	private static final String systemAccid="10086";
	
	@Autowired
	private TeamCreateLogService teamCreateLogService;

	@Autowired
	private SpecialRelationService specialRelationService;

	@Autowired
	private UserRelationService userRelationService;

	@Autowired
	private UserService userService;

    private static final Logger log = LoggerFactory.getLogger(WyService.class);

    @Override
    public String registUser(User user) throws CFException {
        WyUserCreateRequest createRequest = new WyUserCreateRequest();
        createRequest.setAccid(user.getUser_no());
        createRequest.setIcon(user.getPic());
        createRequest.setName(user.getNick_name());

        try {
            WyUserCreateResponse response = WyHelper.execute(createRequest);
            if (response.isSuccess()) {
            	//第一次更新用户名片
            	updateUser(user);
                return response.getInfo().getToken();

            } else {
                return refreshToken(user);

            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new CFException(FailCode.APP, e.getMessage());

        }
    }
    
    @Override
    public void updateUser(User user) throws CFException {
        try {
        	JSONObject props=new JSONObject();
        	props.put("id", user.getId());
        	props.put("super_id", user.getSuper_id());
        	
    		WyUserUpdateUinfoRequest request=new WyUserUpdateUinfoRequest();
    		request.setName(user.getNick_name());
    		request.setAccid(user.getUser_no());
    		request.setIcon(user.getPic());
    		request.setMobile(user.getMobile());
            request.setEx(props.toJSONString());
            excuteDefaultRequest(request);

        } catch (Exception e) {
            e.printStackTrace();
            throw new CFException(FailCode.APP, e.getMessage());

        }
    }
    

    @Override
    public String refreshToken(User user) throws CFException {
        WyUserRefreshTokenRequest request = new WyUserRefreshTokenRequest();
        request.setAccid(user.getUser_no());

        try {
            WyUserRefreshTokenResponse response = WyHelper.execute(request);
            if (response.isSuccess()) {
                return response.getInfo().getToken();

            } else {
                throw new WyException(response);

            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new CFException(FailCode.APP, e.getMessage());

        }
    }

    @Override
    public String createTeam(Family family) throws IOException, WyException {
        WyTeamCreateRequest request=new WyTeamCreateRequest();
        request.setTname(family.getName());
        request.setOwner(family.getOwner_user_no());
        List<String> memberList = Arrays.asList(family.getOwner_user_no());
        String memberJson = JSONArray.toJSONString(memberList);
        request.setMembers(memberJson);
        request.setMsg("欢迎你加入本家族");
        request.setIcon(family.getFicon());
        request.setMagree(0);
        request.setAnnouncement("");
        request.setBeinvitemode(1);
        request.setInvitemode(1);
        request.setUptinfomode(1);
        request.setUpcustommode(1);

        WyTeamCreateResponse response = WyHelper.execute(request);
        if (response.isSuccess()) {
        	teamCreateLogService.save(response.getTid(),family.getOwner_user_no(),family.getType());
            return response.getTid();

        } else {
            throw new WyException(response);

        }
    }

    @Override
    public void updateTeam(Family family, String icon, String familyName, String announcement)  throws CFException {
    	WyTeamUpdateRequest request=new WyTeamUpdateRequest();
		request.setTid(family.getTid());
		request.setOwner(family.getOwner_user_no());
/*		if(StringUtils.isNotBlank(family.getAnnouncement())){
			request.setAnnouncement(family.getAnnouncement());
		}*/
		if(StringUtils.isNotBlank(icon)){
			request.setIcon(icon);
		}
		if(StringUtils.isNotBlank(familyName)){
			request.setTname(familyName);
		}
		
		excuteDefaultRequest(request);
    }

    @Override
    public void removeTeam(String tid, String ownerNo) throws CFException {
        WyTeamRemoveRequest request = new WyTeamRemoveRequest();
        request.setTid(tid);
        request.setOwner(ownerNo);

        excuteDefaultRequest(request);
    }

    @Override
    public void shieldFamily(Family family, String user_no,Integer shield) throws CFException {
    	JSONObject json=new JSONObject();
    	
    	if(shield==1){
    		json.put("type", 1);
    		json.put("userNo", user_no);
    		WyTeamKickRequest request = new WyTeamKickRequest();
	        request.setTid(family.getTid());
	        request.setOwner(family.getOwner_user_no());
	        request.setMember(user_no);
	        request.setAttach(json.toJSONString());
	        excuteDefaultRequest(request);
    	}else if(shield==0){
    		json.put("type", 0);
    		json.put("userNo", user_no);
    		 WyTeamAddRequest request=new WyTeamAddRequest();
             request.setTid(family.getTid());
             request.setOwner(family.getOwner_user_no());
             request.setMembers(JSONArray.toJSONString(Arrays.asList(user_no)));
             request.setMsg("欢迎加入" + family.getName() + "家族");
             request.setAttach(json.toJSONString());
             excuteDefaultRequest(request);
    	}
    	
    }
    
    @Override
    public void addTeamMember(Family family, String uno) throws CFException {
        addTeamMembers(family, Arrays.asList(uno));
    }

    @Override
    public void addTeamMembers(Family family, List<String> userList) throws CFException {
        int index = 0;
        do {
            int eindex = index + 200;
            if (eindex > userList.size()) {
                eindex = userList.size();
            }

            WyTeamAddRequest request=new WyTeamAddRequest();
            request.setTid(family.getTid());
            request.setOwner(family.getOwner_user_no());
            List<String> list = userList.subList(index, eindex);
            request.setMembers(JSONArray.toJSONString(list));
            request.setMsg("欢迎加入" + family.getName() + "家族");

            try {
                WyDefaultResponse response = WyHelper.execute(request);
                if (!response.isSuccess()) {
                    throw new WyException(response);
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new CFException(FailCode.APP, e.getMessage());

            }

            index = eindex + 1;
        } while (index < userList.size());
    }

    @Override
    public void removeTeamMember(String tid, String owner, String uno) throws CFException {
        WyTeamKickRequest request = new WyTeamKickRequest();
        request.setTid(tid);
        request.setOwner(owner);
        request.setMember(uno);

		excuteDefaultRequest(request);
    }

    @Override
    public void leaveTeam(String tid, String uno) throws CFException {
        WyTeamLeaveRequest request = new WyTeamLeaveRequest();
        request.setTid(tid);
        request.setAccid(uno);

		excuteDefaultRequest(request);
    }

    @Override
    public void muteTeamMember(String tid, String ownerNo, String memberNo, int mute) throws CFException {
        WyTeamMuteTlistRequest request = new WyTeamMuteTlistRequest();
        request.setTid(tid);
        request.setOwner(ownerNo);
        request.setAccid(memberNo);
        request.setMute(mute);

        excuteDefaultRequest(request);
    }

    @Override
    public void  muteTeam(String tid, String userNo, int nocall) throws CFException {
    	 int ope = nocall == 0 ? 2 : 1;
    	WyTeamMuteTeamRequest request = new WyTeamMuteTeamRequest();
        request.setTid(tid);
    	request.setAccid(userNo);
    	request.setOpe(ope);
        excuteDefaultRequest(request);
    }
   
    @Override
    public void sendMsgForHongBao(String userNo, String tid, JSONObject body) throws CFException {
		WyMsgSendMsgRequest request = new WyMsgSendMsgRequest();
		request.setFrom(userNo);
		request.setTo(tid);
		request.setOpe(1);
		request.setType(100);
		request.setBody(body.toJSONString());
    	excuteDefaultRequest(request);
    }
    
    private <T extends WyResponse> void excuteDefaultRequest(WyRequest<T> request) throws CFException {
		T response = null;
		int repeatCount = 0;
		do {
			try {
				response = WyHelper.execute(request);
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (!response.isSuccess()) {
				repeatCount++;
				log.error("execut wy fail url={}, code={}, msg={} ",  request.getUrl(), response.getCode(), response.getDesc());
				if (response.getCode().equalsIgnoreCase("416")) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				} else {
					return;

				}
			}

			if (repeatCount > 3) {
				throw new WyException(response);
			}

		} while (!response.isSuccess());
	}

	@Override
	public void checkTeamMember(Family family, FamilyMember familyMember,String userNo) {
		if( family.getOwner_user_no().equals(userNo)){
			return;
		}
		Integer shield = familyMember.getShield();
		
		Integer mute = familyMember.getMute();
		try {
			WyTeamJoinTeamsRequest request = new WyTeamJoinTeamsRequest();
			request.setAccid(userNo);
			WyTeamJoinTeamsResponse response = WyHelper.execute(request);
			if(response.isSuccess()){
				List<TeamJoinTeams> infos = response.getInfos();
				boolean has=false;
				if(infos!=null && !infos.isEmpty()){
					for (TeamJoinTeams teamJoinTeams : infos) {
						String tid = teamJoinTeams.getTid();
						String owner = teamJoinTeams.getOwner();
						log.debug("checkTeam========>{}, {}", family, family.getTid());
						if(family.getTid().equals(tid)){
							has = true;
							ckeckTeamMute(family, userNo, mute);
							
						}else{
							leaveTeam(tid, userNo);
						}
					}
				}
				boolean isShield = shield == null || shield == 0;
				if(!has && isShield){
					addTeamMember(family, userNo);
					ckeckTeamMute(family, userNo, mute);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();

		}
		return;
	}
	
	

	private void ckeckTeamMute(Family family, String userNo, Integer mute) throws ParseException, IOException, CFException {
		
			WyTeamListTeamMuteRequest request=new WyTeamListTeamMuteRequest();
			request.setOwner(family.getOwner_user_no());
			request.setTid(family.getTid());
			WyTeamListTeamMuteResponse response = WyHelper.execute(request);
			if(response.isSuccess()){
				int isMute=0;
				List<TeamListTeamMute> list = response.getMutes();
				if(list!=null && !list.isEmpty()){
					for (TeamListTeamMute teamListTeamMute : list) {
						String accid = teamListTeamMute.getAccid();
						if(accid.equals(userNo)){
							isMute=1;
							break;
						}
					}
				}
				mute = mute != null && mute == 1 ? 1 : 0;
				if (!mute.equals(isMute)) {
					muteTeamMember(family.getTid(), family.getOwner_user_no(),userNo, mute);
				}
			}
	}

	@Override
	public void setSpecialRelation(String userNo, String targetUserNo, int relationType, int value) throws CFException {
		log.info("setSpecialRelation============>request={}, target={}, relationType={}, value={}", userNo, targetUserNo, relationType, value);
    	try {
			WyUserSetSpecialRelationRequest request=new WyUserSetSpecialRelationRequest();
			request.setAccid(userNo);
			request.setTargetAcc(targetUserNo);
			request.setRelationType(relationType);
			request.setValue(value);
			excuteDefaultRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void pushMessageForTeam(String from, String to, String content,
			JSONObject ext) throws CFException {
		WyMsgSendAttachMsgRequest request=new WyMsgSendAttachMsgRequest();
		request.setFrom(from);
		request.setTo(to);
		request.setMsgtype(1);
		if(content!=null && !"".equals(content)){
			request.setPayload(content);
			request.setPushcontent(content);
		}
		if(ext!=null){
			request.setAttach(ext.toJSONString());
		}
		excuteDefaultRequest(request);
	}
	
	@Override
	public void pushMessageForUser(String userNo, String content,
			JSONObject ext) throws CFException {
		WyMsgSendAttachMsgRequest request=new WyMsgSendAttachMsgRequest();
		request.setFrom(systemAccid);
		request.setTo(userNo);
		request.setMsgtype(0);
		if(content!=null && !"".equals(content)){
			request.setPayload(content);
			request.setPushcontent(content);
		}
		if(ext!=null){
			request.setAttach(ext.toJSONString());
		}
		excuteDefaultRequest(request);
	}
	
	@Override
	public void sendMsgForTeam(String from, String to,String content,
			JSONObject ext) throws CFException {
		WyMsgSendMsgRequest request=new WyMsgSendMsgRequest();
		JSONObject body=new JSONObject();
		body.put("msg", content);
		request.setFrom(from);
		request.setTo(to);
		request.setOpe(1);
		request.setType(10);
		request.setBody(body.toJSONString());
		if(ext!=null){
			request.setExt(ext.toJSONString());
		}
		excuteDefaultRequest(request);
	}

	@Override
	public void sendMsgForTeam(String from, String to, String content, JSONObject ext, Boolean push) throws CFException {
		WyMsgSendMsgRequest request = new WyMsgSendMsgRequest();
		JSONObject body = new JSONObject();
		body.put("msg", content);
		request.setFrom(from);
		request.setTo(to);
		request.setOpe(1);
		request.setType(10);
		request.setBody(body.toJSONString());
		if (ext != null) {
			request.setExt(ext.toJSONString());
		}
		// 设置option的值  取消掉通知
		JSONObject option = new JSONObject();
		option.put("push", push);
		option.put("roam",true);
		option.put("history",true);
		option.put("sendersync",true);
		option.put("route",true);
		option.put("badge",true);
		option.put("needPushNick",true);
		option.put("persistent",true);

		request.setOption(option.toJSONString());
		excuteDefaultRequest(request);
	}

	@Override
	public void sendMsgForUser(String form,String to,Integer type,String content,JSONObject ext) throws CFException {
		WyMsgSendMsgRequest request=new WyMsgSendMsgRequest();
		JSONObject body=new JSONObject();
		body.put("msg", content);
		request.setFrom(form);
		request.setTo(to);
		request.setOpe(0);
		request.setType(type);
		request.setBody(body.toJSONString());
		if(ext!=null){
			request.setExt(ext.toJSONString());
		}
		excuteDefaultRequest(request);
	}
	@Override
	public void sayHello(User user, User tuser, String hi) throws CFException {
		String content="你已经添加"+tuser.getNick_name()+",现在可以开始聊天了";
		JSONObject json=new JSONObject();
		json.put("userNo", tuser.getUser_no());
		if(StringUtils.isNotEmpty(hi)){
			this.sendMsgForUser(tuser.getUser_no(),user.getUser_no(), 0,hi, json);
			this.sendMsgForUser(tuser.getUser_no(),user.getUser_no(),10, "以上是打招呼的内容", json);
		}
		this.sendMsgForUser(tuser.getUser_no(),user.getUser_no(),10, content, json);
		
	}


	@Override
	public void sendVideoMsgForUser(User form, User to) throws CFException {
		
    	String msg = form.getNick_name()+"请求添加您为好友";
    	JSONObject option = new JSONObject();
    	option.put("needPushNick", true);

		JSONObject body = new JSONObject();
		body.put("video",1); // 1表示响起语音
		body.put("message_type", MsgEunm.newFriendApplay.getMsgtype());
		body.put("pushType", 1);

		log.debug("发送好友申请==========》 form={},to={}", form, to);
		WyMsgSendAttachMsgRequest request = new WyMsgSendAttachMsgRequest();

		request.setFrom("10086");
		request.setTo(to.getUser_no());
		request.setMsgtype(0);
		request.setOption(option.toJSONString());
		request.setAttach(body.toJSONString());
		request.setPayload(body.toJSONString());
		request.setPushcontent(msg);
		excuteDefaultRequest(request);
	}

	@Override
	public void updateFriend(String user_no, String target_user_no, String alias, JSONObject json) throws CFException {
		WyFriendUpdateRequest request=new WyFriendUpdateRequest();
		request.setAccid(user_no);
		request.setFaccid(target_user_no);
		if (StringUtils.isEmpty(alias)) {
			request.setAlias(null);

		} else {
			request.setAlias(alias);

		}
		
		if(json!=null){
			request.setEx(json.toJSONString());
		}
		try {
			WyHelper.execute(request);

		} catch (ParseException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		}

		log.debug("updateRelationExpand============>user_no={}, target={},alias={},json={}", user_no,  target_user_no, alias,json);
	}

	@Override
	public void addFriend(String user_no, String target_user_no) throws CFException {
    	log.debug("addFriend============>request={}, target={}", user_no, target_user_no);
		WyFriendAddRequest request=new WyFriendAddRequest();
		request.setAccid(user_no);
		request.setFaccid(target_user_no);
		request.setType(1);
		try {
			WyHelper.execute(request);
		}  catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteFriend(String user_no, String target_user_no) {
		WyFriendDeleteRequest request=new WyFriendDeleteRequest();
		request.setAccid(user_no);
		request.setFaccid(target_user_no);
		try {
			WyHelper.execute(request);
			deleteFriendItem(user_no, target_user_no);
			deleteFriendItem(target_user_no, user_no);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private void deleteFriendItem(String user_no, String target_user_no) throws CFException {
			setSpecialRelation(user_no, target_user_no, SpecialRelationConstant.relation_type_black, SpecialRelationConstant.relation_value_blackMute);
			updateRelationExpand(user_no, target_user_no);
			sendUpdateFriend(user_no);
	}

	@Override
	public void updateRelationExpand(String userNo, String tuserNo) throws CFException {
		User user = userService.findByUserNo(userNo);
		User tuser = userService.findByUserNo(tuserNo);

		updateFriendItem(user, tuser);
		updateFriendItem(tuser, user);
	}

	private void updateFriendItem(User user, User tuser) throws CFException {
		boolean isFriend = userRelationService.isFriend(user.getId(), tuser.getId());
		if (isFriend) {
			UserRelation userRelation = userRelationService.getUserRelation(user.getId(), tuser.getId());
			boolean isBack1 = specialRelationService.isBlack(user.getId(), tuser.getId());
			boolean isBack2 = specialRelationService.isBlack(tuser.getId(),user.getId());
			JSONObject json = new JSONObject();
			if(isBack1){
				json.put("is_show_alert", true);
			}else if(isBack2){
				json.put("is_show_alert", false);
			}
			updateFriend(user.getUser_no(), tuser.getUser_no(), userRelation.getFriend_remark(), json);
		}
	}

	@Override
	public void sendUpdateFriend(String userNo) throws CFException {
		JSONObject json=new JSONObject();
		json.put("message_type", MsgEunm.updateFriend.getMsgtype());
		log.debug("更新好友=====================================================》userNo={}",userNo);
//		pushMessageForUser(userNo, "", json);
	}

	@Override
	public boolean changeOwner(String tid, String owner, String newowner) {
		WyTeamChangeOwnerRequest request=new WyTeamChangeOwnerRequest();
		request.setTid(tid);
		request.setOwner(owner);
		request.setNewowner(newowner);
		request.setLeave(1);
		try {
			WyDefaultResponse response = WyHelper.execute(request);
			return response.isSuccess();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
